<template>
  <div class="node_setting">
    <div class="setting-title">表输入</div>
    <div class="setting_item">
      <el-form :model="form" label-width="110px">
        <el-form-item label="源表" required>
          <!-- <el-input v-model="form.tableName" @blur="validateNodeName" /> -->
          <el-select v-model="form.tableName" placeholder="请选择源表" @change="handleChange">
            <el-option v-for="item in tableListOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- <div class="setting_item_title"></div> -->
        <el-form-item label="字段内容：">
          <!-- <el-select v-model="keyword" filterable placeholder="输入字段名查询" style="width: 240px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select> -->
        </el-form-item>
        <el-form-item ref="tableContainerRef" class="table_infinite_list">
          <el-table
            ref="tableRef"
            class="infinite-list-item"
            :data="form.tableData"
            height="450"
            style="width: 100%"
            :row-key="(row) => row.name"
            :reserve-selection="true"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="name" label="字段名" width="150" />
            <el-table-column fixed prop="typeName" label="字段类型" width="150" />
            <el-table-column fixed prop="comment" label="备注" width="150" />
          </el-table>
        </el-form-item>
      </el-form>
      <!-- 保存按钮 -->
      <el-button class="mt-4" type="primary" @click="saveData">保存</el-button>
    </div>
  </div>
</template>
<script lang="ts">
export default { name: "TableInputSetting" };
</script>
<script setup lang="ts">
import { baseAction, auditMoreAction } from "../../index";
import LogicFlow from "@logicflow/core";
import { MyLogicFlowPropertiesType } from "@/types/logic-flow";
import IndicatorManageAPI, {
  TableInfoParameter,
  TableInfoResponse,
  FieldColumnsConfig,
  TableListParameter,
} from "@/api/strategy/strategy-index-database";
const props = defineProps<{
  lf?: LogicFlow;
  data: LogicFlow.NodeData | LogicFlow.EdgeData;
  parameter: TableListParameter;
}>();
const tableListOptions = ref<string[]>();
const tableInfoParameter = reactive<TableInfoParameter>({ id: 0, table: "" });
const tableInfoResponse = ref<TableInfoResponse>();
// 存储选中数据的字段名，而非行索引
const selectedFieldNames = ref<string[]>([]);
const tableRef = ref();
const form = ref({
  tableName: "",
  fieldContent: "",
  tableData: [] as FieldColumnsConfig[],
});
const tableContainerRef = ref<HTMLElement | null>(null);

// 解析props.data.properties数据辅助函数
function parseProperties(properties: MyLogicFlowPropertiesType) {
  return {
    tableName: properties.tableName || "",
    tableData: properties.tableData || "",
  };
}

watch(
  () => props.data,
  (newVal) => {
    console.log("props.data changed:", newVal);
    const { tableName, fieldContent, tableData } = newVal.properties as MyLogicFlowPropertiesType;
    form.value = {
      tableName: tableName || "",
      fieldContent: fieldContent || "",
      tableData: tableData || [],
    };
    props.lf?.setProperties(newVal.id, {
      ...form.value,
    });
    // 初始化选中状态
    selectedFieldNames.value = form.value.tableData
      .filter((row: any) => row.isSelected)
      .map((row) => row.name)
      .filter((name): name is string => name !== undefined);
    // 确保表格数据更新后再设置选中状态
    nextTick(() => {
      if (tableRef.value) {
        form.value.tableData.forEach((row: any) => {
          if (row.isSelected) {
            tableRef.value.toggleRowSelection(row, true);
          }
        });
      }
    });
  },
  {
    immediate: true,
  }
);

async function handleQuery() {
  tableListOptions.value = await IndicatorManageAPI.TableList(props.parameter);
}

async function handleChange() {
  tableInfoParameter.id = props.parameter.id;
  tableInfoParameter.table = form.value.tableName;
  try {
    const response = await IndicatorManageAPI.TableInfo(tableInfoParameter);
    tableInfoResponse.value = response;
    form.value.tableData = response.columns!.map((row: any) => ({
      ...row,
      isSelected: selectedFieldNames.value.includes(row.name),
    }));
    // 确保表格数据更新后再设置选中状态
    await nextTick();
    if (tableRef) {
      form.value.tableData.forEach((row: any) => {
        if (row.isSelected) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
    }
  } catch (error) {
    // 处理请求错误，例如提示用户
    console.error("请求表结构数据失败:", error);
  }
}

// 处理勾选框变化
const handleSelectionChange = (selectedItems: [{ name: string; typeName: string }]) => {
  selectedFieldNames.value = selectedItems.map((item) => item.name); // 更新已选中的行数据
  //  手动更新表格的选中状态
  nextTick(() => {
    if (tableRef.value) {
      form.value.tableData.forEach((row: any) => {
        tableRef.value.toggleRowSelection(row, selectedFieldNames.value.includes(row.name));
      });
    }
  });
};

// 定义自定义事件
const emits = defineEmits<{
  (event: "dataFetched", data: any): void;
}>();

// 保存操作
const saveData = () => {
  if (selectedFieldNames.value.length === 0) {
    ElMessage.warning("请选择数据"); // 提示用户选择数据
    return;
  } else {
    // 只输出选中的字段名和字段类型
    const selectedData = form.value
      .tableData!.filter((row: any) => selectedFieldNames.value.includes(row.name))
      .map((row) => ({
        name: row.name,
        typeName: row.typeName,
      }));
    emits("dataFetched", selectedData);
    // 手动触发数据更新
    form.value = {
      ...form.value,
      tableData: form.value.tableData!.map((row: any) => {
        const isSelected = selectedFieldNames.value.includes(row.name);
        return {
          ...row,
          // 根据选择状态更新字段，示例
          isSelected: isSelected,
        };
      }),
    };
    props.lf?.setProperties(props.data.id, {
      ...form.value,
      tableData: form.value.tableData,
    });
    // 确定表格数据更新后再设置勾选状态
    nextTick(() => {
      if (tableRef.value) {
        form.value.tableData.forEach((row: any) => {
          if (row.isSelected) {
            tableRef.value.toggleRowSelection(row, true);
          }
        });
      }
    });
    ElMessage.success("数据已保存"); // 提示用户选择数据
  }
  // 手动触发LogicFlow的属性变化事件
  if (props.lf) {
    console.log("触发事件");
    props.lf.emit("node:change:properties", {
      data: props.data,
      oldProperties: {}, // 可以传入旧属性用于比较
      newProperties: props.data.properties,
    });
  }
};

watch(
  form,
  (newForm) => {
    // 监听form数据变化，执行更新逻辑
    if (props.lf && props.data.id) {
      props.lf.setProperties(props.data.id, newForm);
    }
  },
  {
    deep: true,
  }
);

onMounted(() => {
  if (!tableListOptions.value?.length) {
    handleQuery();
  }
  nextTick(() => {
    if (tableContainerRef.value) {
      const containerHeight = tableContainerRef.value.offsetHeight;
      const newMaxHeight = containerHeight - 50; // 减去一些额外的空间，可根据实际情况调整
      tableContainerRef.value.style.maxHeight = `${newMaxHeight}px`;
      tableContainerRef.value.style.overflowY = "auto";
    }
  });
});
</script>
<style lang="scss" scoped>
.setting-title {
  padding: 10px 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e9e9e9;
}

.setting-item {
  .setting-item-title {
    padding: 10px 0;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #e9e9e9;
  }

  .table_infinite_list {
    height: calc(100% - 20px);
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .table_infinite_list .table_infinite_list_item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    // background: var(--el-color-primary-light-9);
    margin: 10px;
    // color: var(--el-color-primary);
  }

  .table_infinite_list .table_infinite_list_item + .list-item {
    margin-top: 10px;
  }
}
</style>
